#!/usr/bin/python
# -*- coding: utf-8 -*-

#-----------------------------------------------------------------------------
# Name:        
# Purpose:     
#
# Author:      Administrator
#
# Created:     2006-12-17 下午12:59:02
# RCS-ID:      Id:  
# Copyright:   (c) 2006
# Licence:     Free To Use
#  
#-----------------------------------------------------------------------------
from twisted.application import internet, service
from twisted.web import static, server, vhost, script, http
from twisted.web.resource import Resource
import GameLoaderLicConf
import uuid
from IPy import IP 
import md5
 
def make_random_str():
    _s = md5.new()
    _s.update(str(uuid.uuid4()))
    return _s.hexdigest( ).upper()

def reload_conf():
    reload(GameLoaderLicConf)
    
def gl_httpd_authentication(r):
    ''' check username and password
    
    @param r: a http request
    '''
    
    # auto reload gameloader config
    reload_conf()
    
    # get right username and password
    gl_username = GameLoaderLicConf.GL_WWW_USERNAME
    gl_password = GameLoaderLicConf.GL_WWW_PASSWORD
    
    # get user input username and password
    _username, _password = r.getUser(), r.getPassword()
    
    r.setHeader('WWW-Authenticate', 
                                'Basic realm="GameLoaderLicServ"')
    r.setResponseCode(http.UNAUTHORIZED)
        
    if gl_username == _username and gl_password == _password :
        r.setResponseCode(http.OK)
        return http.OK
    else:
        r.setResponseCode(http.UNAUTHORIZED)
        return http.UNAUTHORIZED
    
class GameLoaderLicRoot(Resource):
    isLeaf = True
    
    def render(self, request):
        
        if gl_httpd_authentication(request) == http.OK:
            return '''OK-%s''' % make_random_str()
        else:
            return '''UNAUTHORIZED-%s''' % make_random_str()


class GameLoaderInitWord(Resource):
    
    def render(self, request):
        
        if gl_httpd_authentication(request) == http.OK:
            reload_conf()
            return GameLoaderLicConf.GL_INIT_WORD
        else:
            return '''UNAUTHORIZED-%s''' % make_random_str()
        

root = vhost.NameVirtualHost()

lic_root = GameLoaderLicRoot()

root.putChild('glinit', GameLoaderInitWord())

# Add a default -- htdocs
root.default=lic_root

# Add a simple virtual host -- foo.com
root.addHost("lic.rorer.org", lic_root)

application = service.Application('web')
sc = service.IServiceCollection(application)
site = server.Site(root)
i = internet.TCPServer(80, site) 
i.setServiceParent(sc)